<?php
/**
 * Created by zhangxw.
 * File_name: UseraccesstokenBehavior.php
 * Date: 2015/5/28
 */

namespace Common\Behavior;
use Think\Behavior;

class UseraccesstokenBehavior extends Behavior{
    public function run(&$params){
        if(empty($params)){
            return;
        }
        $log_info = I();
        $logPath = '/tmp/logs/public.useraccesstoken.filter.' . date('Y-m-d') . '.log';
        \Think\Log::write(json_encode($log_info), 'authorize', '', $logPath);
        //获取请求的token
        $token = I('param.access_token');

        //验证token
        if (empty($token))
        {
            $log_info['action'] = 'check';
            $log_info['action_result'] = 'fail';
            \Think\Log::write(json_encode($log_info), 'authorize', '', $logPath);
            echo json_encode(array('error' => 'invalid_request')); exit;
        }

        $dsn = C('mongo_pool.mongo');
        try
        {
            $mongo = new Mongo('mongodb://'.$dsn['server'].'/'.$dsn['db']);
            $mongo = $mongo->selectDB($dsn['db']);
            $token_stored = $mongo->tokens->findOne(array("_id" => $token));
        }
        catch(Exception $ex)
        {
            $log_info['action'] = 'mongodb';
            $log_info['action_result'] = 'fail';
            \Think\Log::write(json_encode($log_info), 'authorize', '', $logPath);
            echo json_encode(array('error' => 'temporarily_unavailable')); exit;
        }
        if(!$token_stored)
        {
            $log_info['action'] = 'token_stored';
            $log_info['action_result'] = 'fail';
            \Think\Log::write(json_encode($log_info), 'authorize', '', $logPath);
            echo json_encode(array('error' => 'expired_token')); exit;
        }
        if($token_stored['expires'] < time())
        {
            $log_info['action'] = 'expires';
            $log_info['action_result'] = 'fail';
            \Think\Log::write(json_encode($log_info), 'authorize', '', $logPath);
            echo json_encode(array('error' => 'expired_token')); exit;
        }
        if(($token_stored['client_equipment_no'] || $client_equipment_no) && $token_stored['client_equipment_no'] <> $client_equipment_no)
        {
            $log_info['action'] = 'client_equipment_no';
            $log_info['action_result'] = 'fail';
            \Think\Log::write(json_encode($log_info), 'authorize', '', $logPath);
            echo json_encode(array('error' => 'changed_equipment')); exit;
        }
        $log_info['action'] = 'end';
        $log_info['action_result'] = 'succ';
        $log_info['user_id'] = $token_stored['user_id'];
        $log_info['token_stored'] = $token_stored;
        \Think\Log::write(json_encode($log_info), 'authorize', '', $logPath);

        //获取user_id
        $user_id = $token_stored['user_id'];
        C('user_id',$user_id);
    }
}